package com.hdsx.netty.tomcatserver.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author 占贤银
 * time 2024/8/5 22:58
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class NettyTomcat {

    private int port;

    private Properties prop = new Properties();

    private Map<String, XYServlet> handlerMappings = new HashMap<>(10);

    public NettyTomcat(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new NettyTomcat(8888).start();
    }

    public void start() {
        try {
            initNetty();
            startNetty();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    private void startNetty() {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            // 主线程组主要负责接收请求
            bossGroup = new NioEventLoopGroup();
            // 从线程组主要负责处理Handler
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel client)
                                throws Exception {
                            // todo 责任链模式 定义一些pipeline
                            ChannelPipeline pipeline = client.pipeline();
                            // 编码
                            pipeline.addLast(new HttpResponseEncoder());
                            // 解码器
                            pipeline.addLast(new HttpRequestDecoder());
                            pipeline.addLast(new GPTomcatHandler(handlerMappings));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = bootstrap.bind(this.port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bossGroup != null) {
                bossGroup.shutdownGracefully();
            }
            if (workerGroup != null) {
                workerGroup.shutdownGracefully();
            }
        }
    }

    public void initNetty() {
        InputStream in = null;
        try {
            in = this.getClass().getClassLoader().getResourceAsStream("web.properties");
            prop.load(in);
            for (Object k : prop.keySet()) {
                String key = k.toString();
                if (key.endsWith("url")) {
                    String servletUrl = key.replaceAll("url", "");
                    String url = prop.getProperty(key);
                    String className = prop.getProperty(servletUrl + "className");
                    XYServlet xyServlet = (XYServlet) Class.forName(className).newInstance();
                    xyServlet.init();
                    handlerMappings.put(url, xyServlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
